#include "drv_systick.h"
#include "drv_clock.h"
#include "stm32f0xx_ll_cortex.h"
#include "stm32f0xx_ll_utils.h"

/// systick 全局对象
struct 
{
    TDrv_Systick_OnTickEvent _OnTickEvent;     /// 时基更新事件
    UInt32                   _tick;            /// 内部tick
}_g_drv_systick;

void SysTick_Handler(void)
{
    _g_drv_systick._tick++;
    if (_g_drv_systick._OnTickEvent.event != NULL)
        _g_drv_systick._OnTickEvent.event(_g_drv_systick._OnTickEvent.param);
}

void Drv_Systick_Init(void)
{
    _g_drv_systick._OnTickEvent.event = NULL;
    _g_drv_systick._OnTickEvent.param = NULL;
    LL_Init1msTick(Drv_Clock_Frequency());  ///< 1ms时基
    LL_SYSTICK_EnableIT();                  ///< 启动systick
}

void Drv_Systick_DeInit(void)
{
    // LL_SYSTICK_DisableIT();
    // _g_drv_systick._OnTickEvent.event = NULL;
    // _g_drv_systick._OnTickEvent.param = NULL;
}

UInt32 Drv_Systick_GetTick(void)
{
    return _g_drv_systick._tick;
}

void Drv_Systic_SetTickEvent(TDrv_Systick_OnTickEvent event)
{
    LL_SYSTICK_DisableIT();
    _g_drv_systick._OnTickEvent.event = event.event;
    _g_drv_systick._OnTickEvent.param = event.param;
    __DMB();    ///< 保证_OnTickEvent写入内存
    LL_SYSTICK_EnableIT();                  ///< 启动systick
}
